import { createRouter, createWebHistory } from 'vue-router'
import LoginView from '@/views/LoginView.vue'
import WechatCallbackView from '@/views/WechatCallbackView.vue'
import AccountBindView from '@/views/AccountBindView.vue'
import HomeView from '@/views/HomeView.vue'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      name: 'Home',
      component: HomeView,
      meta: { requiresAuth: true },
    },
    {
      path: '/login',
      name: 'Login',
      component: LoginView,
    },
    {
      path: '/wechat-callback',
      name: 'WechatCallback',
      component: WechatCallbackView,
    },
    {
      path: '/bind-account',
      name: 'AccountBind',
      component: AccountBindView,
      props: route => ({
        openid: route.query.openid,
        nickname: route.query.nickname,
        avatar: route.query.avatar,
      }),
    },
  ],
})

// 路由守卫 - 登录验证
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('token')

  if (to.matched.some(record => record.meta.requiresAuth) && !isAuthenticated) {
    next({ name: 'Login' })
  } else {
    next()
  }
})

export default router
